<template>
  <div :id="'edit'+keyname">
    <el-upload
      accept="image/*"
      :action="uploadUrlr"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      name="image"
      :show-file-list="false"
      :headers="headers"
      style="display: none"
      ref="upload"
      v-if="this.uploadUrlr"
    >
    </el-upload>

    <VueUeditorWrap ref='VueUeditor' v-model="contents" :config="myConfig" style="width: 100%; line-height: 1;" />
  </div>
</template>

<script>
  // 百度编辑器
  import VueUeditorWrap from 'vue-ueditor-wrap'
  import $ from "jquery";

  export default {
    name: "Editor",
    components: {
      VueUeditorWrap
    },
    props: {
      content: '',
      is_tk:{
        type:String,
        default:'0'
      },
      keyname:{
        type:String,
        default:''
      },
    },
    data() {
      return {
        headers: {
          'user-authorization':this.getState().token,
        },
        uploadUrlr:this.http + "/api/Public/upload_img",
        contents: '',
        myConfig: {
          toolbars: [
            [
              // 'undo', //撤销
              // 'redo', //重做
              'bold', //加粗
              'italic', //斜体
              'underline', //下划线
              'strikethrough', //删除线
              'source', //源代码
              'pasteplain', //纯文本粘贴模式
              'selectall', //全选
              'removeformat', //清除格式
              // 'fontfamily', //字体
              'fontsize', //字号
              'paragraph', //段落格式
              'justifyleft', //居左对齐
              'justifyright', //居右对齐
              'justifycenter', //居中对齐
              'justifyjustify', //两端对齐
              'forecolor', //字体颜色
              'backcolor', //背景色
              'simpleupload',
              'insertorderedlist', //有序列表
              'insertunorderedlist', //无序列表
            ]
          ],
          autoHeightEnabled: true, // 编辑器不自动被内容撑高
          initialFrameHeight: 200, // 初始容器高度
          initialFrameWidth: '100%', // 初始容器宽度
          UEDITOR_HOME_URL: '/static/ueditor/',
          allowDivTransToP: false
        },
        times:[],  // 标志符
        is_load:false
      };
    },
    watch: {
      content: {
        handler(val) {
          if (val !== this.contents) {
            this.contents = val === null ? "" : val;
          }
        },
        immediate: true,
      },
    },
    mounted() {
      const _this=this;
      let load_time=setInterval(()=>{
        if($('#edit'+_this.keyname+' .edui-for-simpleupload').length>0){
          clearInterval(load_time)
          let id=$('#edit'+_this.keyname+' .edui-for-simpleupload').attr('id');
          $('#edit'+_this.keyname+' .edui-for-simpleupload').html(`
            <div id="`+id+`_state" class="edui-default"><div class="edui-button-wrap edui-default"><div id="`+id+`_body" unselectable="on" title="图片上传" class="edui-button-body edui-default"><div class="edui-box edui-icon edui-default"></div></div></div></div>
          `)
          function get_tk_line(){
            let fram=$('#edit'+_this.keyname+' .edui-editor-iframeholder iframe');
            let tk_line=$('#edit'+_this.keyname+' .edui-editor-iframeholder iframe').contents().find('.tk_line');
            let times=[]
            for(let i=0;i<tk_line.length;i++){
              times.push(tk_line.eq(i).attr('data-time'))
            }
            return times
          }
          if(this.is_tk==1){
            let editor = this.$refs.VueUeditor.editor;
            editor.addListener('contentChange',function(e){
              if(!_this.is_load){
                _this.is_load=true;
                _this.times=[...get_tk_line()];
                return false;
              }
              let items=get_tk_line();
              // 对比之前的，找到删除的是哪一个
                if(items.length<_this.times.length){
                  for(let i=_this.times.length-1;i>=0;i--){
                    if(items.indexOf(_this.times[i])==-1){
                      _this.$emit('dele_item',i)
                    }
                  }
                }
                // 找到新增的是哪个
                if(items.length>_this.times.length){
                  for(let i=0;i<items.length;i++){
                    if(_this.times.indexOf(items[i])==-1){
                      _this.$emit('add_item',{i,time:items[i]})
                    }
                  }
                }
                _this.times=[...items];
            });
          }
        }
      },30)

      $(document).on('click', '#edit'+_this.keyname+' .edui-for-simpleupload', function(e) {
        _this.$refs.upload.$children[0].$refs.input.click();
      })
    },
    beforeDestroy(){
      const _this=this;
      $(document).off('click', '#edit'+_this.keyname+' .edui-for-simpleupload')
    },
    methods: {
      handleUploadSuccess(res, file) {
        // 获取富文本组件实例
        let editor = this.$refs.VueUeditor.editor;
        // 如果上传成功
        if (res.status == 200) {
          editor.execCommand('insertHtml', '<img src="'+this.http+'/'+res.message+'" />')
        } else {
          this.$message.error("图片插入失败");
        }
      },
      handleUploadError() {
        this.$message.error("图片插入失败");
      },
      add_item(html) {
        let editor = this.$refs.VueUeditor.editor;
        editor.execCommand('insertHtml', html)
      },
      get_content() {
        let editor = this.$refs.VueUeditor.editor;
        return editor.getContent()
      }
    },
  };
</script>

<style>

</style>
